<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8"/>
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
        <title>AJ Utils-StreamHelper Tutorial</title>
        <meta name="description" content="Small Java utilities with many useful functions. Utility methods for stream operations and conversions" />
        <meta name="keywords" content="AJ Utils, ajaxjs, ajaxjs framework, java utilities, tools, helper, stream operations,I/O,Java" />
        <meta name="viewport" content="width=device-width, initial-scale=1"/>
        <link rel="stylesheet" href="https://framework.ajaxjs.com/static/new-ui/css/common.css" />
        <link rel="stylesheet" href="https://iam.ajaxjs.com/asset/main.css"/>
        <link rel="icon" type="image/x-icon" href="https://framework.ajaxjs.com/aj-logo/logo.ico"/>
        <script src="https://framework.ajaxjs.com/static/aj-docs/common.js"></script>
        <script>
            // 获取用户的默认语言
            var userLang = navigator.language || navigator.userLanguage;

            // 检查是否为中文环境（包括简体和繁体）
            if (userLang.startsWith('zh') && location.pathname.indexOf('cn') == -1) {
                 confirm('欢迎！您可以改为访问中文内容。是否继续？') && location.assign('/cn');  // 如果是中文，则弹出提示
            }

            var _hmt = _hmt || [];
            (function() {
              var hm = document.createElement("script");
              hm.src = "https://hm.baidu.com/hm.js?208c5aea11c52991bd1c3283e62ad0ce";
              var s = document.getElementsByTagName("script")[0];
              s.parentNode.insertBefore(hm, s);
            })();
        </script>
    </head>
    <body>
        <nav>
            <div>
                <div class="links">
                    <a href="/">🏠 Home</a>
                    | ⚙️ Source:
                    <a target="_blank" href="https://github.com/lightweight-component/aj-util">Github</a>/<a target="_blank" href="https://gitcode.com/lightweight-component/aj-util">Gitcode</a>
                    | 🚀 <a href="/cn">Chinese Version</a>
                </div>
                <h1>
                    <img src="https://framework.ajaxjs.com/aj-logo/logo.png" style="vertical-align: middle;height: 45px;margin-bottom: 6px;" />
                    AJ Utils
                </h1>
                <h3>Small Java Utils Library</h3>
            </div>
        </nav>
        <div>
            <menu>
                
                <ul>
                    <li class="selected">
                        <a href="/">Home</a>
                    </li>
                </ul>
                <h3>Common</h3>
                <ul>
                    <li><a href="/common/JsonUtil/">JsonUtil</a></li>
                    <li><a href="/common/BytesHelper/">BytesHelper</a></li>
                    <li><a href="/common/ConvertBasicValue/">ConvertBasicValue</a></li>
                    <li><a href="/common/MessageDigestHelper/">HashHelper</a></li>
                    <li><a href="/common/MapTool/">MapTool</a></li>
                    <li><a href="/common/ObjectHelper/">ObjectHelper</a></li>
                    <li><a href="/common/RandomTools/">RandomTools</a></li>
                    <li><a href="/common/RegExpUtils/">RegExpUtils</a></li>
                    <li><a href="/common/StrUtil/">StrUtil</a></li>
                    <li><a href="/common/BoxLogger/">BoxLogger</a></li>
                    <li><a href="/common/BytesHelper/">BytesHelper</a></li>
                    <li><a href="/common/EncodeTools/">UrlEncode</a></li>
                    <li><a href="/common/XmlHelper/">XmlHelper</a></li>
                    <li><a href="/common/WebUtils/">WebUtils</a></li>
                </ul>
                <h3>Date Handing</h3>
                <ul>
                    <li><a href="/date/intro/">Introduction</a></li>
                    <li><a href="/date/convert/">Date Converter</a></li>
                    <li><a href="/date/formatter/">Date Formatter</a></li>
                </ul>
                <h3>Reflection</h3>
                <ul>
                    <li><a href="/reflect/Methods/">Methods</a></li>
                    <li><a href="/reflect/Types/">Types</a></li>
                    <li><a href="/reflect/Clazz/">Clazz</a></li>
                </ul>

                <h3>IO</h3>
                <ul>
                    <li><a href="/io/FileHelper/">FileHelper</a></li>
                    <li><a href="/io/Resources/">Resources</a></li>
                    <li><a href="/io/StreamHelper/">DataReader/DataWriter</a></li>
                    <li><a href="/io/ZipHelper/">ZipHelper</a></li>
                </ul>

                <h3>HTTP Request</h3>
                <ul>
                    <li><a href="/http_request/Get">HTTP Request</a></li>
                    <li><a href="/http_request/advanced-usage/">Advanced Usage</a></li>
                    <li><a href="/http_request/Base/">Base</a></li>
                </ul>
    
               <h3>Cryptography</h3>
               <ul>
                <li><a href="/cryptography/intro/">Introduction</a></li>
                <li><a href="/cryptography/flow/">Basic Flow</a></li>
                <li><a href="/cryptography/AesCrypto/">AES/DES</a></li>
                <li><a href="/cryptography/RsaCrypto/">RSA</a></li>
               </ul>
            </menu>
            <article class="aj-text">
                <h1>DataReader Tutorial</h1>
<p>DataReader  is a reader class for reading data from an input stream. It supports reading raw byte data from sources such as files, network sockets, or memory buffers, while providing functionality for handling both text and binary data.</p>
<h2>Main Features</h2>
<ol>
<li><strong>Multiple Data Reading Methods</strong>: Supports various reading methods including byte streams, text lines, and complete strings</li>
<li><strong>Character Encoding Support</strong>: Character encoding can be specified, defaults to UTF-8</li>
<li><strong>Streaming Processing</strong>: Supports chunked processing of large files to avoid memory overflow</li>
<li><strong>Functional Programming</strong>: Uses functional interfaces to process read data</li>
</ol>
<h2>Basic Usage</h2>
<h3>1. Creating Instances</h3>
<pre><code class="language-java">// Create instance with default UTF-8 encoding
InputStream inputStream = new FileInputStream(&quot;example.txt&quot;);
DataReader reader = new DataReader(inputStream);

// Create instance with specified character encoding
DataReader readerWithEncoding = new DataReader(inputStream, StandardCharsets.UTF_8);
</code></pre>
<h3>2. Reading Byte Data</h3>
<pre><code class="language-java">// Read stream data as bytes
InputStream inputStream = new FileInputStream(&quot;large-file.bin&quot;);
DataReader reader = new DataReader(inputStream);

reader.readStreamAsBytes(8192, (readSize, buffer) -&gt; {
    // Process the read data
    System.out.println(&quot;Read &quot; + readSize + &quot; bytes of data&quot;);
    // Can process data in buffer here
});
</code></pre>
<h3>3. Reading Text Lines</h3>
<pre><code class="language-java">// Read text data line by line
InputStream inputStream = new FileInputStream(&quot;text-file.txt&quot;);
DataReader reader = new DataReader(inputStream);

reader.readAsLineString(line -&gt; {
    System.out.println(&quot;Read a line: &quot; + line);
    // Process each line of text
});
</code></pre>
<h3>4. Reading Complete String</h3>
<pre><code class="language-java">// Read entire input stream as string
InputStream inputStream = new FileInputStream(&quot;text-file.txt&quot;);
DataReader reader = new DataReader(inputStream);

String content = reader.readAsString();
System.out.println(&quot;File content: &quot; + content);
</code></pre>
<h3>5. Reading Byte Array</h3>
<pre><code class="language-java">// Read entire input stream as byte array
InputStream inputStream = new FileInputStream(&quot;binary-file.bin&quot;);
DataReader reader = new DataReader(inputStream);

byte[] bytes = reader.readAsBytes();
System.out.println(&quot;Byte array length: &quot; + bytes.length);
</code></pre>
<h3>Notes</h3>
<ol>
<li>The <code>readStreamAsBytes</code> method automatically closes the input stream when reading is complete</li>
<li>All methods throw <code>UncheckedIOException</code> when IO errors occur</li>
<li>For large file processing, it's recommended to use the <code>readStreamAsBytes</code> method for chunked processing</li>
<li>The <code>readAsString</code> method appends a newline character at the end of each line</li>
</ol>
<h1>DataWriter Tutorial</h1>
<p>DataWriter is a writer class for writing data to an output stream. It supports writing raw byte data to destinations such as files, sockets, or buffers, and provides buffering functionality to improve write efficiency.</p>
<h2>Main Features</h2>
<ol>
<li><strong>Multiple Data Writing Methods</strong>: Supports copying data from input streams, writing byte arrays, etc.</li>
<li><strong>Buffering Support</strong>: Buffering functionality is enabled by default to improve write performance</li>
<li><strong>Flexible Byte Array Writing</strong>: Supports writing complete byte arrays or specified ranges of data</li>
<li><strong>No Automatic Stream Closing</strong>: Does not automatically close output streams, managed by the caller</li>
</ol>
<h2>Basic Usage</h2>
<h3>1. Creating Instances</h3>
<pre><code class="language-java">// Create DataWriter instance
OutputStream outputStream = new FileOutputStream(&quot;output.txt&quot;);
DataWriter writer = new DataWriter(outputStream);
</code></pre>
<h3>2. Copying Data from Input Stream</h3>
<pre><code class="language-java">// Copy data from input stream to output stream
InputStream inputStream = new FileInputStream(&quot;input.txt&quot;);
OutputStream outputStream = new FileOutputStream(&quot;output.txt&quot;);
DataWriter writer = new DataWriter(outputStream);

writer.write(inputStream); // Copy data
// Note: Need to manually close streams
inputStream.close();
outputStream.close();
</code></pre>
<h3>3. Writing Byte Arrays</h3>
<pre><code class="language-java">// Write complete byte array
byte[] data = &quot;Hello World&quot;.getBytes();
OutputStream outputStream = new FileOutputStream(&quot;output.txt&quot;);
DataWriter writer = new DataWriter(outputStream);

writer.write(data);
outputStream.close();
</code></pre>
<h3>4. Writing Specified Range of Byte Array</h3>
<pre><code class="language-java">// Write specified range of byte array
byte[] data = &quot;Hello World&quot;.getBytes();
OutputStream outputStream = new FileOutputStream(&quot;output.txt&quot;);
DataWriter writer = new DataWriter(outputStream);

// Write 5 bytes starting from offset 2
writer.write(data, 2, 5); // Write &quot;llo W&quot;
outputStream.close();
</code></pre>
<h2>Configuration Options</h2>
<pre><code class="language-java">// Disable buffering (not recommended)
OutputStream outputStream = new FileOutputStream(&quot;output.txt&quot;);
DataWriter writer = new DataWriter(outputStream);
writer.setBuffered(false);
</code></pre>
<h2>Notes</h2>
<ol>
<li>DataWriter does not automatically close output streams, the caller needs to manually manage stream closing</li>
<li>Buffering is enabled by default, disabling buffering will give a warning prompt</li>
<li>All methods throw <code>UncheckedIOException</code> when IO errors occur</li>
<li>When both offset and length are 0, the <code>write(byte[], int, int)</code> method writes the entire byte array</li>
</ol>

            </article>
        </div>

       <footer>
            AJ-Util, a part of <a href="https://framework.ajaxjs.com" target="_blank">AJ-Framework</a> open source. Mail:
            frank@ajaxjs.com, visit <a href="https://blog.csdn.net/zhangxin09" target="_blank">my blog(In Chinese)</a>.
            <br />
            <br />
            Copyright © 2025 Frank Cheung. All rights reserved.
        </footer>
    </body>
</html>